import Vue from 'vue'
import Vuex from 'vuex';
import { userInfoAPI } from '@/api'
import { removeToken } from '@/utils/auth'

Vue.use(Vuex);
import { setToken } from '@/utils/auth'
import { getToken } from '../utils/auth';
const store = new Vuex.Store({
    state: () => ({
        tokenObj: getToken() || {},
        userInfo: {}
    }),

    mutations: {
        // 提供一个修改的方法
        saveToken(state, payload) {
            // 把传进来的token对象赋值给tokenObj
            state.tokenObj = payload
                // 储存到本地储存
            setToken(payload)
        },
        setUserInfo(state, payload) {
            state.userInfo = payload
        },
        logout(state) {
            state.tokenObj = {}
            state.userInfo = {}
            removeToken()
        }
    },
    actions: {
        async reqUserInfo(context) {
            if (!context.state.userInfo.name) {
                let res = await userInfoAPI()
                context.commit('setUserInfo', res.data.data)
            }
        }
    }

});
export default store